package cn.thinkluck.pattern.observier.subscriber;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 事件总线
 * @Author liutao
 * @DateTime 2024/7/30 下午9:18
 */
public class EventBus {
    //维护事件与订阅者之间的关系
    private final Map<String, List<Subscriber>> subscribers = new HashMap<>();

    /**
     * 注册订阅
     * @param event 事件
     * @param subscriber 订阅者
     */
    public void registerSubscriber(String event, Subscriber subscriber) {
        //如果事件不存在，则创建一个事件
        subscribers.putIfAbsent(event, new ArrayList<>());
        //将订阅者添加到事件中
        subscribers.get(event).add(subscriber);
    }

    /**
     * 移除订阅
     * @param event 事件
     * @param subscriber 订阅者
     */
    public void removeSubscriber(String event, Subscriber subscriber) {
        List<Subscriber> subscriberList = subscribers.get(event);
        if (subscriberList != null) {
            subscriberList.remove(subscriber);
        }
    }

    /**
     * 发布事件
     * @param event 事件
     * @param param 参数
     */
    public void publishEvent(String event,Object param) {
        List<Subscriber> subscriberList = subscribers.get(event);
        if (subscriberList != null) {
            for (Subscriber subscriber : subscriberList) {
                subscriber.onEvent(param);
            }
        }
    }
}
